<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" fullscreen :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" class="fullHeight" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120" label-position="right">
            <el-row :gutter="1">
                <el-col :span="20">
                    <el-row :gutter="1">
                        <el-col :span="8">
                            <el-form-item label="采购单号" prop="contract_code">
                                <el-input v-model="form.contract_code" placeholder="采购单号" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16" style="display:flex;justify-content: flex-end;">
                            <el-button type="primary" @click="add">新增</el-button>
                            <el-button type="primary" @click="save">保存</el-button>
                            <!-- <sc-print-button :selection="[{id:form.id}]" style="margin-right:12px"></sc-print-button> -->
                            <el-button type="warning" @click="deliver" :disabled="form.id == '' || form.send_status ==1">发货</el-button>
                            <el-button type="warning" @click="receive" :disabled="form.id == '' || form.is_receive ==1">付款</el-button>
                            <el-button type="warning" @click="invoice" :disabled="form.id == '' || form.is_ticket ==2">开票</el-button>
                            <el-button type="success" @click="print" :disabled="form.id == ''" v-if="pirnt">打印</el-button>
                            <sc-print-button :selection="[{id:form.id}]" ref="saleprint" v-if="!pirnt"></sc-print-button>
                            <sc-check-button :apiObj="checkObj" @checkSuccess="checkSuccess" :selection="[{id:form.id}]" v-if="form.status != 1"></sc-check-button>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="8">
                            <el-form-item label="供应商" prop="apply_id">
                                <el-select v-model="form.apply_id" placeholder="请选择" filterable clearable @change="applytChange"> 
                                    <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8"></el-col>
                        <el-col :span="8">
                            <el-form-item label="开单日期" prop="open_single">
                                <el-date-picker v-model="form.open_single" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="8">
                            <el-form-item label="供应商地址">
                                <el-input v-model="apply_address" placeholder="供应商地址" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8"></el-col>
                        <el-col :span="8">
                            <el-form-item label="发货仓库" prop="ware_id">
                                <el-select v-model="form.ware_id" filterable style="width: 100%" placeholder="发货仓库" @change="outChange" clearable>
                                    <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="8">
                            <el-form-item label="供应商电话">
                                <el-input v-model="apply_phone" placeholder="供应商电话" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="联系人" prop="linkman">
                                <el-input v-model="linkman" placeholder="供应商电话" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="发货物流及单号" prop="send_goods_no">
                                <el-input v-model="form.send_goods_no" placeholder="发货物流及单号" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-col :span="8">
                        <el-form-item label="发货日期" prop="send_date">
                            <el-date-picker v-model="form.send_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                        </el-form-item>
                    </el-col>
                    <el-row :gutter="1">
                        <el-col :span="12">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" placeholder="备注" type="textarea" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" style="padding-bottom: 20px;">
                            <el-form-item label="附件" prop="enclosure">
                                <sc-upload-file v-model="form.enclosure" :limit="1">
                                    <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                                </sc-upload-file>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="4" v-if="form.id">
                    <div>
                        <el-tag style="margin: 0 10px 15px;" :type="is_print && is_print.type">{{is_print && is_print.text}}</el-tag>
                    </div>
                    <div>
                        <el-tag style="margin: 0 10px 15px;" :type="send_status && send_status.type">{{send_status && send_status.text}}</el-tag>
                    </div>
                    <div>
                        <el-tag style="margin: 0 10px 15px;" :type="is_ticket && is_ticket.type">{{is_ticket && is_ticket.text}}</el-tag>
                    </div>
                    <div>
                        <el-tag style="margin: 0 10px 15px;" :type="is_receive && is_receive.type">{{is_receive && is_receive.text}}</el-tag>
                    </div>
                    <div>
                        <el-tag style="margin: 0 10px 15px;" :type="status && status.type">{{status && status.text}}</el-tag>
                    </div>
                </el-col>
            </el-row>
            <el-col :span="24">
				<el-form-item label="产品清单" prop="order_detail">
					<el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button>
					<sc-form-table ref="table" v-model="form.order_detail" :addTemplate="addTemplate" placeholder="暂无数据" @deleteTable="deleteTable" height="350" show-summary>
						<el-table-column label="品名" align="center" width="150">
							<template #default="scope">
								<el-input
                                    v-if="!scope.row.goods_id" 
                                    v-model="scope.row.goods_name" 
                                    placeholder="品名" 
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'goods_name')"
                                    @keydown.up="up(scope.$index, 'goods_name')"
                                    @keydown.down="down(scope.$index, 'goods_name')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'goods_name')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'goods_name')"
                                    :id="`goods_name${scope.$index}`"
                                    :ref="`goods_name${scope.$index}`"
                                ></el-input>
								<span v-else>
									{{ scope.row.goods_name?scope.row.goods_name:'' }}
								</span>
							</template>
						</el-table-column>
						<el-table-column label="规格" align="center" width="230">
							<template #default="scope">
								<el-input 
                                    v-model="scope.row.goods_spec" 
                                    placeholder="规格" 
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'goods_spec')"
                                    @keydown.up="up(scope.$index, 'goods_spec')"
                                    @keydown.down="down(scope.$index, 'goods_spec')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'goods_spec')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'goods_spec')"
                                    :id="`goods_spec${scope.$index}`"
                                    :ref="`goods_spec${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
						<el-table-column label="单位" align="center" width="120">
							<template #default="scope">
								<!-- <el-select v-if="!scope.row.goods_id" v-model="scope.row.unit_id" filterable style="width: 100%" placeholder="请选择">
									<el-option v-for="item in unitList" :key="item.id" :label="item.unit_name" :value="item.id" />
								</el-select>
								<span v-else>
									{{ scope.row.unit_name?scope.row.unit_name:'' }}
								</span> -->
                                <el-input 
                                    v-model="scope.row.unit" 
                                    placeholder="单位" 
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'unit')"
                                    @keydown.up="up(scope.$index, 'unit')"
                                    @keydown.down="down(scope.$index, 'unit')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'unit')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'unit')"
                                    :id="`unit${scope.$index}`"
                                    :ref="`unit${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
						<el-table-column label="数量" prop="sale_num" align="center" width="120">
							<template #default="scope">
								<el-input 
                                    v-model="scope.row.sale_num" 
                                    placeholder="数量" 
                                    @input="totalCompute" 
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'sale_num')"
                                    @keydown.up="up(scope.$index, 'sale_num')"
                                    @keydown.down="down(scope.$index, 'sale_num')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'sale_num')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'sale_num')"
                                    :id="`sale_num${scope.$index}`"
                                    :ref="`sale_num${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
						<el-table-column label="单价" align="center" width="120">
							<template #default="scope">
								<el-input 
                                    v-model="scope.row.price" 
                                    placeholder="单价" 
                                    @input="totalCompute"
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'price')"
                                    @keydown.up="up(scope.$index, 'price')"
                                    @keydown.down="down(scope.$index, 'price')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'price')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'price')"
                                    :id="`price${scope.$index}`"
                                    :ref="`price${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
						<el-table-column label="金额" prop="total_price" align="center" width="150">
                            <template #default="scope">
								<el-input 
                                    v-model="scope.row.total_price" 
                                    placeholder="金额" 
                                    @input="feeCompute"
                                    @focus="onFocus($event)"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'total_price')"
                                    @keydown.up="up(scope.$index, 'total_price')"
                                    @keydown.down="down(scope.$index, 'total_price')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'total_price')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'total_price')"
                                    :id="`total_price${scope.$index}`"
                                    :ref="`total_price${scope.$index}`"
                                ></el-input>
							</template>
                        </el-table-column>
						<el-table-column label="备注" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.remark" placeholder="备注"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'remark')"
                                    @keydown.up="up(scope.$index, 'remark')"
                                    @keydown.down="down(scope.$index, 'remark')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'remark')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'remark')"
                                    :id="`remark${scope.$index}`"
                                    :ref="`remark${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
                        <el-table-column label="订单号码" align="center" width="230">
							<template #default="scope">
								<el-input 
                                    v-model="scope.row.order_number" 
                                    placeholder="订单号码"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'order_number')"
                                    @keydown.up="up(scope.$index, 'order_number')"
                                    @keydown.down="down(scope.$index, 'order_number')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'order_number')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'order_number')"
                                    :id="`order_number${scope.$index}`"
                                    :ref="`order_number${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
						<el-table-column label="备注2" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.remark2" placeholder="备注2"
                                    @keydown.enter="handleArrowRightKey(scope.$index, 'remark2')"
                                    @keydown.up="up(scope.$index, 'remark2')"
                                    @keydown.down="down(scope.$index, 'remark2')"
                                    @keydown.left="handleArrowLeftKey(scope.$index, 'remark2')"
                                    @keydown.right="handleArrowRightKey(scope.$index, 'remark2')"
                                    :id="`remark2${scope.$index}`"
                                    :ref="`remark2${scope.$index}`"
                                ></el-input>
							</template>
						</el-table-column>
					</sc-form-table>
				</el-form-item>
			</el-col>
            <el-row :gutter="1">
				<el-col :span="4">
					<el-form-item label="结算账户" prop="settlement_id">
						<el-select v-model="form.settlement_id" filterable clearable placeholder="请选择账户" style="width:100%">
							<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="本单应收" prop="total_price">
						<el-input v-model="form.total_price" placeholder="本单应收" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="本次付款" prop="pay_price">
						<el-input v-model="form.pay_price" placeholder="本次付款" clearable :disabled="form.is_stages == 1"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add' || mode == 'copy'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</el-footer>
	</el-dialog>
	<select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
	<setting-money v-if="dialog.setting" ref="settingDialog" @success="handleSetting" @closed="dialog.setting=false"></setting-money>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
import settingMoney from "@/views/procure/order/settingMoney.vue";
import store from "@/store";
export default {
	components: {settingMoney, selectGoods,},
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增采购订单',
				copy: '新增采购订单',
				edit: '编辑采购订单',
				show: '查看采购订单'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
				id: "",
				apply_id: "",
				open_single: this.moment().format('YYYY-MM-DD'),
				deliver_date: "",
				// is_tax: "",
				is_ticket: "",
				ship_name: "",
				send_date: "",
				send_goods_no: "",
				remark: "",
				enclosure: "",
				status: "",
				order_detail: [],
				total_price: "",
				pay_price: 0,
				settlement_id: "",
				is_stages: 0,
				stages_all: [],
				is_check: 0,
				has_discount: '',
				total_amount: 0,
				discount_num: null,
                ware_id: "",
                type: 2
			},
			//验证规则
			rules: {
				apply_id: [{required: true, message: '请选择客户'}],
				// contacts: [{required: true, message: '请选择联系人'}],
				// deliver_date: [{required: true, message: '请选择送货日期'}],
				// send_date: [{required: true, message: '请选择发货日期'}],
			},
			contactList: [],
			dialog: {
				goods: false,
				client: false,
			},
			cateProps: {
				value: "id",
				label: "cate_name",
				checkStrictly: true
			},
			accountList: [],
			addTemplate: {
				goods_name:'',
				goods_spec:'',
				unit_id:'',
				sale_num:'',
				price:'',
				total_price:'',
				order_number:'',
				remark:'',
				remark2:''
			},
			unitList:[],
            status: {},
            send_status: {},
            is_ticket: {},
            is_receive: {},
            is_print: {},
            column: [
                {prop: "goods_name",name: "品名",},
                {prop: "goods_spec",name: "规格",},
                {prop: "unit",name: "单位",},
                {prop: "sale_num",name: "数量",},
                {prop: "price",name: "单价",},
                {prop: "total_price",name: "金额",},
                {prop: "remark",name: "备注",},
                {prop: "order_number",name: "订单号码",},
                {prop: "remark2",name: "备注2",},
            ],
            wareList: [],
			checkObj: this.$API.procure.order.check,
			applyList: [],
            apply_address: "",
            apply_phone: "",
            linkman: "",
            pirnt: true,
		}
	},
	mounted() {
        store.commit("setMenuName", "采购单")
		this.getAccount() // 账号
		this.getUnit()
        this.getWare()
		this.getApply();
	},
	methods: {
        checkSuccess(){
            this.setData({id:this.form.id})
        },
		/**获取单位*/
		async getUnit(){
			var res = await this.$API.goods.goodsUnit.all.get();
			this.unitList = res.data
		},
        // 获取仓库
        async getWare() {
            var res = await this.$API.goods.ware.all.get();
            this.wareList = res.data;
            if (this.mode == 'add') {
                res.data.map(item => {
                    if (item.is_default == 1) {
                        this.form.ware_id = item.id
                    }
                })
            }
        },
        /* 供应商列表 */
        async getApply() {
			var res = await this.$API.apply.apply.all.get();
			this.applyList = res.data
		},
		/**分期设置金额成功事件*/
		handleSetting(data) {
			this.form.stages_all = data
		},
		/**设置分期按钮点击*/
		openStage() {
			if (this.form.total_amount <= 0) {
				this.$message.error("当前金额为0！")
				return;
			}
			this.dialog.setting = true
			this.$nextTick(() => {
				this.$refs.settingDialog.open('add').setData(this.form)
			})
		},
		/**设置分期*/
		stagesChange() {
			console.log(this.form.is_stages)
			if (this.form.is_stages == 1) {
				this.form.pay_price = 0
			} else {
				// this.form.pay_price = this.form.total_amount
				this.form.stages_all = []
			}
		},
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.form.is_check = e
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.procure.order.edit.post(this.form);
					} else {
						res = await this.$API.procure.order.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.visible = false;
						this.$emit('success', this.form, this.mode)
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data, value) {
			var res = await this.$API.procure.order.detail.get({id: data.id});
			if (!value) {
				this.form.id = data.id
				this.form.contract_code = res.data.contract_code
			}
			this.form.apply_id = res.data.apply_id
			// this.customer_name = res.data.customer.customer_name
			// this.customer_address = res.data.customer.address
			// this.customer_phone = res.data.customer.mobile
			this.form.contacts = res.data.contacts
			this.form.open_single = res.data.open_single
			this.form.deliver_date = res.data.deliver_date
			// this.form.is_tax = res.data.is_tax == 0 ? '' : res.data.is_tax
			this.form.is_ticket = res.data.is_ticket
			this.form.ship_name = res.data.ship_name
			this.form.send_date = res.data.send_date
			this.form.send_goods_no = res.data.send_goods_no
			this.form.remark = res.data.remark
			this.form.ware_id = res.data.ware_id
			if(res.data.enclosure) {
				this.form.enclosure = res.data.enclosure
			}
			// this.form.status = res.data.status
			this.form.total_price = res.data.total_price
			this.form.pay_price = res.data.pay_price
			this.form.settlement_id = res.data.settlement_id
			// this.form.contract_status = res.data.contract_status
			this.form.has_discount = res.data.has_discount
			this.form.discount_num = res.data.discount_num
			this.form.total_amount = res.data.total_amount
			if(res.data.order_detail && res.data.order_detail.length>0) {
				let array = []
				res.data.order_detail.map(item => {
					let data = {
						goods_id: item.goods_id,
						sale_num: item.sale_num,
						price: item.price,
						total_price: item.total_price,
						supplier: item.supplier,
						remark: item.remark,
						unit: item.unit,
						goods_name: item.goods && item.goods.goods_name,
						unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
						cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
						goods_code: item.goods && item.goods.goods_code,
						tax_rate: item.tax_rate,
						goods_spec:item.goods && item.goods.goods_spec,
						unit_id: item.goods && item.goods.unit_id,
						order_number:item.order_number,
						remark2:item.remark2
					}
					if (!value) {
						data.id = item.id
					}
					array.push(data)
				})
				this.form.order_detail = array
			}
			this.form.is_stages = res.data.is_stages
			if (res.data.by_stages && res.data.by_stages.length > 0) {
				res.data.by_stages.map(item => {
					let data = {
						collect_date: item.collect_date,
						collect_rate: item.collect_rate,
						money: item.money,
						remark: item.remark,
						stages_number: item.stages_number
					}
					if (!value) {
						data.id = item.id
					}
					this.form.stages_all.push(data)
				})
			}
            this.form.status = res.data.status
            this.form.send_status = res.data.send_status
            this.form.is_ticket = res.data.is_ticket
            this.form.is_receive = res.data.is_receive
            this.status = res.data.status == 0?{text:'待审核',type:'warning'}: res.data.status == 1?{text:'审核通过',type:'success'}: res.data.status == 2?{text:'审核未通过',type:'danger',reason:res.data.reason}:{text:'',type:''}
            this.send_status = res.data.send_status == 0?{text:'未发货',type:'danger'}: {text:'已发货',type:'primary'}
            this.is_ticket = res.data.is_ticket == 2?{text:'已开票',type:'primary'}: {text:'未开票',type:'danger'}
            this.is_receive = res.data.is_receive == 1?{text:'已付款',type:'primary'}: {text:'未付款',type:'danger'}
            this.is_print = res.data.is_print == 1?{text:'已打印',type:'primary'}: {text:'未打印',type:'danger'}
            this.applytChange(res.data.apply_id)
		},
		onFocus(event) {
			event.target.select();
		},
		checkCustom() {
			this.dialog.client = true
			this.$nextTick(() => {
				this.$refs.clientDialog.open('add')
			})
		},
		clientUpdate(data) {
			console.log(data);
			this.form.customer_id = data.id
			this.customer_name = data.customer_name
			this.customer_address = data.address
			this.customer_phone = data.mobile
			this.getContact(data.id)
		},
		async getContact(e) {
			var res = await this.$API.client.client.detail.get({id: e});
			if(res.data.customer && res.data.customer.length>0) {
				this.contactList = res.data.customer
                this.form.contacts = res.data.customer[0].id
			}
		},
		clearCustom() {
			this.form.customer_id = ""
			this.form.contacts = ""
			this.customer_name = ""
			this.customer_address = ""
			this.customer_phone = ""
			this.contactList = []
		},
		// 选择商品
		checkGoods(e) {
			this.dialog.goods = true
			this.$nextTick(() => {
				this.$refs.goodsDialog.open('add').setData(e)
			})
		},
		goodsUpdate(data) {
            let array = []
            if(Array.isArray(data)){
                data.map((item) => {
                    array.push({
                        goods_id: item.id,
                        goods_name: item.goods_name,
                        cate_name: item.cate_name,
                        unit: item.unit_name,
                        goods_code: item.goods_code,
                        tax_rate: item.tax_rate,
                        supplier: '自产',
                        sale_num: 1,
                        price: item.factory_price,
                        total_price:item.factory_price,
                        cate_id: Number(item.cate_id),
                        unit_id: Number(item.unit_id),
                        goods_spec:item.goods_spec
                    })
                })
            }else {
                array.push({
                    goods_id: data.id,
                    goods_name: data.goods_name,
                    cate_name: data.cate_name,
                    unit: data.unit_name,
                    goods_code: data.goods_code,
                    tax_rate: data.tax_rate,
                    supplier: '自产',
                    sale_num: 1,
                    price: data.factory_price,
                    total_price:data.factory_price,
                    cate_id: Number(data.cate_id),
                    unit_id: Number(data.unit_id),
                    goods_spec:data.goods_spec
                })
            }
            this.form.order_detail = [...this.form.order_detail, ...array]
            this.totalCompute()
		},
		/**表格商品删除事件*/
		deleteTable() {
			this.totalCompute()
		},
		/**折扣方式选择事件*/
		hasChange() {
			this.form.discount_num = null
			this.totalCompute()
		},
		/**折扣率 折扣额 输入事件*/
		discountChange() {
			this.totalCompute()
		},
		/**计算总金额*/
		totalCompute() {
			let count_price = 0
			this.form.total_price = 0
			this.form.order_detail.map(item => {
				if (item.price && item.sale_num) {
					item.total_price = (Number(item.sale_num) * Number(item.price)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
		},
        feeCompute(){
            let count_price = 0
			this.form.total_price = 0
			this.form.order_detail.map(item => {
				if (item.total_price && item.sale_num) {
					item.price = (Number(item.total_price) / Number(item.sale_num)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
        },
		// 账户
		async getAccount() {
			var res = await this.$API.finance.account.all.get();
			this.accountList = res.data;
		},
        // 数量上
        up(index, field) {
            let prevField = ''
            if (index > 0) {
                // const prevField = this.$refs[field][index - 1];
                prevField = this.$refs[`${field}${index-1}`];
            } else {
                prevField = this.$refs[`${field}${this.form.order_detail.length-1}`];
            }
            prevField.focus();
            setTimeout(() => {
                prevField.select();
            },0)
        },
        // 数量下
        down(index, field) {
            let prevField = ''
            if (index < this.form.order_detail.length - 1) {
                prevField = this.$refs[`${field}${index+1}`];
            } else {
                prevField = this.$refs[`${field}${0}`];
            }
            prevField.focus();
            setTimeout(() => {
                prevField.select();
            },0)
        },
        // 数量左
        handleArrowLeftKey(event, field) {
            let newFeield = '';
            for (let i = 0; i < this.column.length; i++) {
                if (field == this.column[0].prop) {
                    newFeield = this.column[this.column.length-1].prop
                }else{
                    if (field == this.column[i].prop) {
                        for (let j = 0; j < this.column.length; j++) {
                            if ( j<i) {
                                newFeield = this.column[j].prop
                            }
                        }
                    }
                }
            }
            console.log('newFeield :>> ', newFeield);
            let prevField = ''
            prevField = this.$refs[newFeield + event];
            if(prevField){
                prevField.focus();
                setTimeout(() => {
                    prevField.select();
                },0)
            }else{
                console.log('无了');
            }
        },
        // 数量右
        handleArrowRightKey(event, field) {
            let newFeield = '';
            for (let i = 0; i < this.column.length; i++) {
                if (field == this.column[this.column.length-1].prop) {
                    newFeield = this.column[0].prop
                }else{
                    if (field == this.column[i].prop) {
                        for (let j = 0; j < this.column.length; j++) {
                            if ( j>i) {
                                newFeield = this.column[j].prop
                                break
                            }
                        }
                    }
                }
            }
            let prevField = ''
            prevField = this.$refs[newFeield + event];
            if(prevField){
                console.log('到了');
                prevField.focus();
                setTimeout(() => {
                    prevField.select();
                },0)
            }else{
                console.log('无了');
            }
        },
        add(){
            for (const key in this.form) {
				this.form[key] = null;
			}
            this.form.open_single = this.moment().format('YYYY-MM-DD'),
            this.form.type = 2
            this.form.enclosure = ""
            this.form.order_detail = []
			this.customer_name = ""
			this.customer_address = ""
			this.customer_phone = ""
			this.contactList = []
            this.wareList.map(item => {
                if (item.is_default == 1) {
                    this.form.ware_id = item.id
                }
            })
        },
        save(){
            this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.procure.order.edit.post(this.form);
					} else {
						res = await this.$API.procure.order.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$message.success("操作成功")
                        this.setData({id: this.form.id ? this.form.id : res.data.id})
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				} else {
					return false;
				}
			})
        },
        async deliver(){
            var reqData = {id: this.form.id}
            var res = await this.$API.procure.order.batchSend.post(reqData);
            if (res.code == 1) {
                this.$message.success("发货成功")
                this.setData({id: this.form.id})
            } else {
                this.$alert(res.message, "提示", {type: 'error'})
            }
        },
        async receive(){
            var reqData = {id: this.form.id}
            var res = await this.$API.procure.order.batchReceive.post(reqData);
            if (res.code == 1) {
                this.$message.success("付款成功")
                this.setData({id: this.form.id})
            } else {
                this.$alert(res.message, "提示", {type: 'error'})
            }
        },
        async invoice(){
            var reqData = {id: this.form.id}
            var res = await this.$API.procure.order.batchTicket.post(reqData);
            if (res.code == 1) {
                this.$message.success("开票成功")
                this.setData({id: this.form.id})
            } else {
                this.$alert(res.message, "提示", {type: 'error'})
            }
        },
        async print(){
            this.pirnt = false
            var reqData = {id: this.form.id}
            var res = await this.$API.procure.order.batchPrint.post(reqData);
            if (res.code == 1) {
                this.$message.success("打印成功")
                this.setData({id: this.form.id})
                this.$refs.saleprint.print()
            } else {
                this.$alert(res.message, "提示", {type: 'error'})
            }
            setTimeout(()=>{
                this.$refs.saleprint.print()
            },500)
        },
        applytChange(e){
            let apply =  this.applyList.find(item=>{return item.apply_id == e})
            console.log('apply :>> ', apply);
			this.apply_address = apply.address
			this.apply_phone = apply.mobile
            this.linkman = apply.linkman
        }
	}
}
</script>

<style>
.fullHeight {
	max-height: 1000px!important;
	overflow: hidden;
	overflow-y: auto;
}
</style>
